package controller

import (
	"ruanGongKeShe16Zu/response"
	"ruanGongKeShe16Zu/service"
	"ruanGongKeShe16Zu/service/vo"
	"strconv"

	"github.com/gin-gonic/gin"
)

type IInstrumentController interface {
	GeneralController
	ListInstrument(ctx *gin.Context)
}

type InstrumentController struct {
	Service service.InstrumentService
}

func NewInstrumentController() IInstrumentController {
	service := service.GetInstrumentService()
	return InstrumentController{
		Service: *service,
	}
}

func (c InstrumentController) Create(ctx *gin.Context) {
	var req vo.InstrumentReq
	if err := ctx.ShouldBind(&req); err != nil {
		response.Fail(ctx, gin.H{"error": err.Error()}, "数据验证错误")
		return
	}
	resp, err := c.Service.Create(ctx, &req)
	if err != nil {
		// utils.LogrusObj.Infoln(err)
		response.Fail(ctx, nil, "创建失败")
		return
	}
	response.Success(ctx, gin.H{"instrument": resp}, "创建成功")
}

func (c InstrumentController) Retrieve(ctx *gin.Context) {
	//获取path中的参数
	instrumentId, _ := strconv.Atoi(ctx.Params.ByName("id"))

	instrument, err := c.Service.Retrieve(ctx, uint(instrumentId))
	if err != nil {
		response.Fail(ctx, nil, "乐器不存在")
		return
	}
	response.Success(ctx, gin.H{"instrument": instrument}, "查询成功")
}
func (c InstrumentController) Update(ctx *gin.Context) {
	//绑定body中的参数
	var requestInstrument vo.InstrumentReq
	if err := ctx.ShouldBind(&requestInstrument); err != nil {
		response.Fail(ctx, nil, "数据验证错误")
		return
	}
	//获取path中的参数
	instrumentId, _ := strconv.Atoi(ctx.Params.ByName("id"))

	updateInstrument, err := c.Service.Retrieve(ctx, uint(instrumentId))
	if err != nil {
		response.Fail(ctx, nil, "乐器不存在")
		return
	}

	//更新分类
	//可传map,struct,name value
	instrument, err := c.Service.Update(ctx, updateInstrument, &requestInstrument)
	if err != nil {
		response.Fail(ctx, nil, "更新失败")
		return
	}
	response.Success(ctx, gin.H{"instrument": instrument}, "更新成功")
}

func (c InstrumentController) Delete(ctx *gin.Context) {
	//获取path中的参数
	instrumentId, _ := strconv.Atoi(ctx.Params.ByName("id"))

	_, err := c.Service.Retrieve(ctx, uint(instrumentId))
	if err != nil {
		response.Fail(ctx, nil, "乐器不存在")
		return
	}

	err = c.Service.Delete(ctx, uint(instrumentId))
	if err != nil {
		response.Fail(ctx, nil, "删除失败，请重试")
		return
	}

	response.Success(ctx, nil, "删除成功")
}

func (c InstrumentController) ListInstrument(ctx *gin.Context) {
	var req vo.ListInstrumentReq
	if err := ctx.ShouldBind(&req); err != nil {
		// 参数校验
		// utils.LogrusObj.Infoln(err)
		response.Fail(ctx, nil, "参数不能为空!")
		return
	}

	resp, err := c.Service.InstrumentList(ctx, &req)
	if err != nil {
		// utils.LogrusObj.Infoln(err)
		response.Fail(ctx, nil, "查询失败")
		return
	}
	response.Success(ctx, gin.H{"Instruments": resp}, "查询成功")
}
